<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">

      <el-col :span="24">
        <el-form-item label="头像">
          <pan-thumb :image="this.avatar"/>
          <!-- 文件上传按钮 -->
          <el-button type="primary" icon="el-icon-upload"
                     @click="imageCropperShow=true">更换头像
          </el-button>
          <image-cropper
            v-show="imageCropperShow"
            :width="300"
            :heigh="300"
            :key="imageCropperKey"
            :url="'http://localhost:9000/zukeApi/sys/oss/uploadImgFile'"
            field="file"
            @close="closeImage"
            @crop-upload-success="cropSuccess"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="部门">
          <el-select
            clearable
            v-model="dataForm.departmentName"
            placeholder="请选择所属部门"
          >
            <el-option :value="departmentDataTree" style="height: auto">
              <el-tree
                :data="departmentDataTree"
                accordion
                node-key="id"
                ref="deptListTree"
                highlight-current
                :props="deptListTreeProps"
                @check-change="deptListTreeCurrentChangeHandle"
                check-on-click-node
              >
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="dataForm.gender">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="密码" prop="password"
                      :class="{ 'is-required': !dataForm.id }" v-show="!dataForm.id">
          <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="确认密码" prop="confirmPassword"
                      :class="{ 'is-required': !dataForm.id }" v-show="!dataForm.id">
          <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="角色" size="mini" prop="roleIdList">
          <el-checkbox-group v-model="dataForm.roleIdList">
            <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{
                role.roleName
              }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="状态" size="mini" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {isEmail, isMobile} from '@/utils/validate'
import ImageCropper from '../../../components/ImageCropper'
import PanThumb from '../../../components/PanThumb'

export default {
  components: {
    ImageCropper,
    PanThumb,
  },
  data () {
    // 校验密码
    let validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    // 校验确认密码
    let validateConformPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    // 校验邮箱
    let validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    // 校验电话
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      // dialog是否弹出
      visible: false,
      // 是否提交完成
      doSuccess: '',
      // 部门
      departmentDataTree: [],
      // 从父组件admin获取的数据
      dataFormFromAdmin: {},
      // 管理员部分数据
      dataForm: {
        id: 0,
        username: '',
        gender: '',
        password: '',
        confirmPassword: '',
        salt: '',
        email: '',
        mobile: '',
        status: 1,
        departmentId: '',
        departmentName: '',
        roleIdList: []
      },
      // 头像
      avatar: '',
      // 部门树型数据
      deptListTreeProps: {
        label: 'name',
        children: 'children'
      },
      // 是否显示上传图片
      imageCropperShow: false,
      // 上传组件id
      imageCropperKey: 0,
      // 角色列表
      roleList: [],
      // 收集最后需要删除的图片
      needToDeleteImg: [],
      // 图片上传成功标记
      cropSuccessFlag: false,
      dataRule: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        confirmPassword: [
          {validator: validateConformPassword, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {validator: validateEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {validator: validateMobile, trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.needToDeleteImg = []
  },
  computed: {
    listenDoSuccess () {
      const {visible, doSuccess, cropSuccessFlag, avatar} = this
      return {visible, doSuccess, cropSuccessFlag, avatar}
    },
    adminInfo: {
      get () { return this.$store.state.user.admin }
    }
  },
  watch: {
    listenDoSuccess (val) {
      // 上传图片成功
      if (val.cropSuccessFlag === true) {
        // 不存放空字符串和重复的值
        if (val.avatar !== '') {
          this.needToDeleteImg.push(val.avatar)
          this.needToDeleteImg.join(',')
          this.needToDeleteImg = Array.from(new Set(this.needToDeleteImg))
        }
        // 操作成功，关闭dialog，删除多余的图片
        if (val.doSuccess === true && val.visible === false) {
          // 将用户选择的图片移除删除的数组中
          this.needToDeleteImg.pop()
          // 判断是否还存在多余无用的图片
          if (this.needToDeleteImg.length > 0) {
            this.deleteFileFromOss(this.needToDeleteImg)
            console.log('操作成功，关闭dialog，删除多余的图片')
          }
          // 添加成功了，但是没有后续操作，直接关闭了dialog，删除全部图片
        } else if (val.doSuccess === '' && val.visible === false) {
          console.log('添加成功了，但是没有后续操作，直接关闭了dialog')
          this.deleteFileFromOss(this.needToDeleteImg)
          // 操作失败，关闭dialog，删除全部图片
        } else if (val.doSuccess === false && val.visible === false) {
          this.deleteFileFromOss(this.needToDeleteImg)
          console.log('操作失败，关闭dialog，删除全部图片')
        }
      }
    }
  },
  methods: {
    init (id) {
      // 有id为修改，没有id则为添加
      this.dataForm.id = id || 0
      this.$http({
        url: this.$http.adornUrl('/sys/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.roleList = data && data.code === 200 ? data.list : []
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        // 更新
        if (this.dataForm.id) {
          this.dataForm.username = this.dataFormFromAdmin.username
          this.dataForm.gender = this.dataFormFromAdmin.gender
          this.dataForm.salt = this.dataFormFromAdmin.salt
          this.dataForm.email = this.dataFormFromAdmin.email
          this.dataForm.mobile = this.dataFormFromAdmin.mobile
          this.dataForm.status = this.dataFormFromAdmin.status
          this.dataForm.departmentId = this.dataFormFromAdmin.departmentId
          this.dataForm.departmentName = this.dataFormFromAdmin.department
          this.dataForm.roleIdList = this.dataFormFromAdmin.roleIdList
          this.avatar = this.dataFormFromAdmin.avatar === null ? '' : this.dataFormFromAdmin.avatar
        } else {
          // 添加
          this.avatar = ''
          this.dataForm.departmentId = ''
          this.dataForm.departmentName = ''
        }
      })

    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/admin/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'userId': this.dataForm.id || undefined,
              'username': this.dataForm.username,
              'gender': this.dataForm.gender,
              'password': this.dataForm.password,
              'salt': this.dataForm.salt,
              'email': this.dataForm.email,
              'mobile': this.dataForm.mobile,
              'status': this.dataForm.status,
              'departmentId': this.dataForm.departmentId,
              'roleIdList': this.dataForm.roleIdList,
              'createUserId': this.adminInfo.userId,
              'avatar': this.avatar
            })
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.doSuccess = true
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.doSuccess = false
              this.$message.error(data.msg)
              // 出现异常，删除oss中文件
              if (this.needToDeleteImg.length > 0) {
                this.deleteFileFromOss(this.needToDeleteImg)
              }
            }
          })
        }
      })
    },
    // 由于种种原因需要删除oss中的文件，保证oss的容量不过载
    deleteFileFromOss (val) {
      this.$http({
        url: this.$http.adornUrl('/sys/oss/deleteUnNeedImg'),
        method: 'post',
        data: this.$http.adornData(val, false)
      }).then(({data}) => {
        if (data && data.code === 200) {
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 部门树选中节点
    deptListTreeCurrentChangeHandle (data, node) {
      this.dataForm.departmentId = data.id
      this.dataForm.departmentName = data.name
    },
    // 上传成功的回调函数
    cropSuccess (data) {
      this.cropSuccessFlag = true
      this.imageCropperShow = false
      // 保存并显示用户选择的图片
      this.avatar = data.url
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imageCropperKey = this.imageCropperKey + 1
    },
    // 关闭上传组件
    closeImage () {
      this.cropSuccessFlag = false
      this.imageCropperShow = false
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imageCropperKey = this.imageCropperKey + 1
    },
    // 数组去重
    unique (arr) {
    },
  }
}
</script>

<style scoped>

</style>
